/* 
 * find the second largest digit in a given integer array
 *
 * ps:
 * as "66, 66, 66, 66, 66", there's no second largest digit;
 * as "99, 99, 88, 86, 68", the second largest digit is 88;
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MINIMUM 0x80000000
int exist;

int
find_second_largest(int *arr, int len)
{
	int max = arr[0];
	int second_max = MINIMUM;
	int i;

	exist = 1;
	for(i=1; i<len; i++) {
		if(arr[i] > max) {
			second_max = max;
			max = arr[i];
		} else if(arr[i]>second_max && arr[i]!=max) /* '&& arr[i]!=max' is important */
			second_max = arr[i];
	}
	if(MINIMUM == second_max)
		exist = 0;
	return second_max;
}

int
main(int argc, char **argv)
{
	int i, len, rt, *arr;
	printf("Enter the length of array: ");
	scanf("%d", &len);
	arr = (int *)malloc(sizeof(int) * len);
	for(i=0; i<len; i++) {
		printf("arr[%d]=", i);
		scanf("%d", arr+i);
	}
	rt = find_second_largest(arr, len);
	if(exist)
		printf("the second largest digit is: %d\n", rt);
	else
		printf("there's no second largest digit\n");

	free(arr);
	return 0;
}
